package com.bjsxt.config.shiro;

import com.bjsxt.domain.User;
import com.bjsxt.service.UserService;
import com.bjsxt.vo.ActiverUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

/**
 * 自定义realm去匹配用户名和密码
 *
 * @ClassName UserRealm
 * @Description TODO
 * @Author xyx
 */
public class UserRealm extends AuthorizingRealm {
    @Lazy
    @Autowired
    private UserService userService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 做认证--登录
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        得到用户登录名
        String phone = token.getPrincipal().toString();
        User user = userService.queryUserByPhone(phone);
        if (null != user) {//若用户存在，则进行下一步，判断密码是否正确
//            将activerUser对象组装存放入redis中
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
//            进行匹配密码
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
            return info;
        } else {
            return null;
        }
    }

    /**
     * 做授权--登录成功之后判断用户是否有某个菜单或者按钮的权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ActiverUser activerUser = (ActiverUser) principalCollection.getPrimaryPrincipal();//身份得到的就是上一个方法的返回值，第一个参数activerUser
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }
}
